﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Shell;
using System.ComponentModel.Design;
using System.IO;
using Microsoft.VisualStudio.TextTemplating.VSHost;
using Microsoft.VisualStudio.TextTemplating;
using ScaffoldIt.Configuration;
using ScaffoldIt.Helpers;
using EnvDTE;

namespace ScaffoldIt.Commands
{
    class ScaffoldItCommand : OleMenuCommand
    {
        public ScaffoldItCommand()
            : base(Callback, new CommandID(GuidList.guidScaffoldItCmdSet, (int)PkgCmdIDList.cmdScaffoldIt))
        {
            this.BeforeQueryStatus += new EventHandler(CmdBeforeQueryStatus);
        }

        void CmdBeforeQueryStatus(object sender, EventArgs e)
        {
            if (ConfigHelpers.HasConfig())
            {
                var DTE = (EnvDTE80.DTE2)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE));
                var items = ((Array)DTE.ToolWindows.SolutionExplorer.SelectedItems)
                    .Cast<UIHierarchyItem>()
                    .Select(h => h.Object as ProjectItem)
                    .Where(i => i != null)
                    .ToList();

                if (items.Count > 0)
                    Visible = items.All(item => item.FileNames[0].EndsWith(".cs") || item.FileNames[0].EndsWith(".vb"));
            }
            else
            {
                Visible = false;
            }
        }

        static void Callback(object sender, EventArgs e)
        {
            ScaffoldItCommand cmd = sender as ScaffoldItCommand;

            ScaffoldingContext ctx = new ScaffoldingContext();
            try
            {
                cmd.Send(ctx);
            }
            catch (Exception ex)
            {
                ctx.Output.WriteLine(ex.ToString());
            }
        }

        private void Send(ScaffoldingContext ctx)
        {
            if (ctx.Init())
            {
                var models = ctx.GetModels();
                if (models == null) return;

                ctx.Scaffold(models);
            }
        }

        
    }
}
